<template>
  <div class="dashboard-container">
    <div class="app-container">
      <el-card class="department-box box-card">
        <!-- 开启栅格 24栅格-->
        <DeptOptions :row="company" :is-root="true" @click-add="onClickAdd" />
        <!-- 树形 -->
        <!-- tree 内部 拿到depts 数组 肯定循环了 循环的每一项 -->
        <!--
          <div v-for="item in data"> <slot :data="item"></slot> </div>
        -->
        <el-tree :data="depts" :props="defaultProps" :default-expand-all="true">
          <!-- 使用插槽的时候, 希望拿到组件内部的数据 -->
          <template v-slot="scope">
            <DeptOptions :row="scope.data" @click-edit="onClickEdit" @click-add="onClickAdd" @ondel="loadDepartments" />
          </template>
        </el-tree>
      </el-card>
    </div>

    <!-- 添加/编辑部门的弹框组件 -->
    <add-dept ref="addDept" :row="deptRow" :show-dialog.sync="dialogVisible" @add-success="loadDepartments" />
  </div>
</template>

<script>
import { getDepartments } from '@/api/departments.js'
import { transListToTree } from '@/utils'
import DeptOptions from './components/dept-options'
import AddDept from './components/dept-add'
import { setTimeout } from 'timers'
export default {
  name: 'Departments',

  components: {
    DeptOptions,
    AddDept
  },
  data() {
    return {
      defaultProps: {
        label: 'name' // 配置渲染的数据字段(默认渲染的数据字段是label)
      },
      company: {}, // 记录公司信息
      depts: [],
      dialogVisible: false,
      deptRow: {}
    }
  },

  created() {
    this.loadDepartments()
  },

  methods: {
    async loadDepartments() {
      const res = await getDepartments()
      this.company = { name: res.companyName, manager: '负责人', children: transListToTree('', res.depts) }
      this.depts = transListToTree('', res.depts)
    },
    // 子组件点击了添加触发
    onClickAdd(data) {
      this.deptRow = data
      this.dialogVisible = true
    },
    // 点击编辑
    onClickEdit(data) {
      this.deptRow = data
      this.dialogVisible = true
      setTimeout(() => {
        this.$refs.addDept.setForm()
      })
    }
  }
}
</script>

<style scoped lang='scss'>
.department-box {
  .el-tree {
    margin-top: 10px;
    border-top: 1px solid #ccc;
  }
}
</style>
